<!-- 订单弹窗 -->
<template>
  <Dialog
    v-model="dialogVisible"
    :maxHeight="'800px'"
    width="60%"
    title="选择订单"
    :before-close="() => closeDialog()"
  >
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('order.customer')">
        <el-input
          v-model="form.username"
          clearable
          :disabled="state.is_customer_name_disabled"
          :placeholder="t('order.customer')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('order.orderCode')">
        <el-input
          v-model="form.order_no"
          clearable
          :placeholder="t('order.orderCode')"
          style="width: 250px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList()">查询</el-button>
        <el-button icon="Refresh" @click="reset(true)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格主体 -->
    <div class="table-container">
      <el-table
        class="m-t-10px"
        :data="dataList"
        highlight-current-row
        stripe
        border
        ref="tableRef"
        v-loading="tableLoading"
        row-key="id"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55"
          :selectable="(row) => Number(row.total_amount) !== 0"
        />
        <el-table-column
          :label="t('order.customer')"
          min-width="200"
          prop="user"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('order.orderCode')"
          prop="order_no"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column :label="t('order.theTypeOfOrder')" :show-overflow-tooltip="true">
          <template #default="{ row }">
            {{ useEnumeratePicker(orderTypeList, row.order_type) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('order.theAmountOfTheOrder')"
          prop="total_amount"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('order.theAmountOfThePayment')"
          prop="pay_amount"
          :show-overflow-tooltip="true"
        />
        <el-table-column :label="t('order.paymentType')" :show-overflow-tooltip="true">
          <template #default="{ row }">
            {{ useEnumeratePicker(paymentTypeList, row.pay_method) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('order.order_category')" :show-overflow-tooltip="true">
          <template #default="{ row }">
            {{ row.order_category == 'order' ? '普通订单' : '经销商订单' }}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit">{{ t('action.increase') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { getOrderEnumApi, getListApi as getOrderListApi } from '@/api/order'
import { getListApi as getwholesalOrderListApi } from '@/api/wholesalOrder'
import { useEnumeratePicker } from '@/utils'
import { Dialog } from '@/components/Dialog'
import { ElMessage } from 'element-plus'
import { getDistributorEnumApi } from '@/api/order/dealerAssetManagement'

const props = withDefaults(defineProps<{ multiple?: boolean }>(), {
  multiple: false // 是否多选
})
const emit = defineEmits(['exposeMultipleData'])
const { t } = useI18n()
const tableRef = ref()

const isReset = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const selectionPak = ref<any[]>([])

const orderTableTypeList = ref<Array<Record<string, any>>>([])

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  username: '',
  user_id: '',
  order_no: '',
  order_type: '',
  delivery_method: '',
  order_status: '', // 订单状态已完成
  pay_status: 3, // 支付状态已支付
  owner: '',
  partner: '',
  date: [],
  start_time: '',
  end_time: '',
  pageIndex: 1,
  pageSize: 15
})
const order_type = ref('order')
const orderTypeList = ref<Array<Record<string, any>>>([])
const paymentTypeList = ref<Array<Record<string, any>>>([])
const userList = ref<Array<Record<string, any>>>([])

const state = reactive({
  is_customer_name_disabled: false
})

//批量勾选
const handleSelectionChange = (val: any[]) => {
  if (val.length > 1 && !props.multiple) {
    // 如果选中的行数超过一行， 并且不允许多选，清除之前的选中项，只保留最新的选中项
    const latestSelection = val[val.length - 1]
    tableRef.value.clearSelection()
    tableRef.value.toggleRowSelection(latestSelection, true)
    multipleSelection.value = [latestSelection]
  } else {
    multipleSelection.value = val
  }
}

//点击添加按钮
const submit = () => {
  if (!multipleSelection.value.length) return ElMessage.warning('请勾选客户')
  if (!props.multiple && multipleSelection.value.length > 1)
    return ElMessage.warning('最多只能勾选一条数据')
  if (props.multiple && isReset.value) {
    const merge = selectionPak.value.concat(multipleSelection.value)
    emit('exposeMultipleData', deduplication(merge), order_type.value)
  } else {
    emit('exposeMultipleData', multipleSelection.value, order_type.value)
  }
  closeDialog()
}

//一维数组去重
const deduplication = (val: any[], key?: string) => {
  if (!val || !val.length) return
  return val.reduce((acc, item) => {
    if (!acc.some((x: Record<string, any>) => x[key ?? 'id'] === item[key ?? 'id'])) {
      acc.push(item)
    }
    return acc
  }, [])
}

//点击取消关闭弹框
const closeDialog = () => {
  reset()
  dialogVisible.value = false
}

//初始化请求
const getList = async (isInitialize?: Boolean) => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))

  delete params.date
  if (order_type.value == 'order') {
    const resp = await getOrderListApi(params)
    dataList.value = resp.data.list
    paginationTotal.value = resp.data.total
  } else {
    const resp = await getwholesalOrderListApi(params)
    resp.data.list.forEach((item) => {
      item.user = item.user_email
    })
    dataList.value = resp.data.list
    paginationTotal.value = resp.data.total
  }
  // 除了第一个其余每次都要清除所选数据
  if (!isInitialize) {
    tableRef.value.clearSelection()
  }
  tableLoading.value = false
}

//重置查询项
const reset = (isRequest?: boolean) => {
  form.value.order_no = ''
  form.value.order_type = ''
  paginationTotal.value = 0
  multipleSelection.value = []
  nextTick(() => {
    tableRef!.value!.clearSelection()
  })
  if (isRequest) {
    getList()
    isReset.value = true
  }
}

//获取枚举
const getDropDownBoxInfo = async () => {
  try {
    const resp = await getOrderEnumApi({ field: 'all' })
    orderTypeList.value = resp.data.order_type
    paymentTypeList.value = resp.data.pay_method

    const userResp = await getDistributorEnumApi({})
    userList.value = userResp.data
  } catch (error) {
    console.error('获取下拉框信息出错:', error)
  }
}
/**
 * 初始化函数
 * @param val - 选中的数据项数组
 * @param customer_name - 客户名称
 * @param isCustomerNameDisabled - 是否禁用客户名称
 * @param orderTableOption - 订单表格的选项
 * @param order_type_params - 订单类型参数（可选）
 */
const initialize = (
  val: any[], // 选中的数据项数组
  customer_name: string, // 客户名称
  isCustomerNameDisabled: boolean, // 是否禁用客户名称
  orderTableOption, // 订单表格的选项
  order_type_params? // 订单类型参数（可选）
) => {
  // 使用 nextTick 确保 DOM 更新完成后执行
  nextTick(() => {
    form.value.username = [String(customer_name)]
    state.is_customer_name_disabled = isCustomerNameDisabled
    orderTableTypeList.value = orderTableOption
    if (order_type_params) {
      // 如果有订单类型参数，更新订单类型
      order_type.value = order_type_params
    }
    getList(true)
  })

  getDropDownBoxInfo() // 初始化下拉框数据

  if (props.multiple) {
    selectionPak.value = val // 如果是多选模式，设置选中的项
  }

  if (!val?.length) return // 如果没有传入值或值为空数组，直接返回

  // 使用 nextTick 确保 DOM 更新完成后选择对应的行
  val.forEach((item: Record<string, any>) => {
    nextTick(() => {
      tableRef?.value?.toggleRowSelection(item, true)
    })
  })
}

defineExpose({
  dialogVisible,
  initialize
})
</script>

<style lang="less" scoped>
.table-container {
  width: 100%;
  overflow-x: auto;

  :deep(.el-table) {
    min-width: 100%;
  }

  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}
</style>
